import { writeFileSync, existsSync, statSync, mkdirSync, readFileSync } from "fs";
import { extname, join, dirname } from "path";
import { getAllFiles } from "./utils/FileUtil";
var crtTime = 0;

function createDirSync(dirPath: string, callback?: () => void) {
    if (existsSync(dirPath)) {
        if (!!callback) {
            callback();
        }
    } else {
        createDirSync(dirname(dirPath), () => {
            mkdirSync(dirPath);
            if (!!callback) {
                callback();
            }
        });
    }
}
export function compress(path: string | string[], exts = ['json'], out?: string | string[], showComplete = true) {
    if (!out) out = path;
    crtTime = Date.now();

    if (typeof path == 'string') {
        if (!existsSync(path)) {
            console.log('no such file or dir');
            return;
        }
        try {
            if (statSync(path).isFile()) {
                console.log('开始压缩json==>', path);

                if (typeof out == 'string') {
                    let obj = JSON.parse(readFileSync(path).toString());
                    createDirSync(join(out));
                    let str = JSON.stringify(obj);
                    writeFileSync(join(out), str);
                    if (showComplete) complete();
                } else {
                    console.log('out path error');
                }
            } else {
                let files = [];
                getAllFiles(path, files, exts);
                for (let i = 0; i < files.length; i++) {
                    const url = files[i];
                    compress(url, exts, url, false);
                    if (i + 1 >= files.length) {
                        complete();
                    }
                }

            }
        } catch (e) {
            console.log(e);
        }
    } else {

        for (let i = 0; i < path.length; i++) {
            const url = path[i]
            compress(url, exts, url, false);
            if (i + 1 >= path.length) {
                complete();
            }
        }

    }
}


function complete() {

    console.log('+------------------------+');
    console.log('|    compress finish!    |');
    console.log('+------------------------+\n');

}